package com.pbc.gmp.action;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.pbc.gmp.commons.base.BaseController;
import com.pbc.gmp.commons.utils.BeanUtils;
import com.pbc.gmp.commons.utils.PageInfo;
import com.pbc.gmp.commons.utils.StringUtils;
import com.pbc.gmp.model.*;
import com.pbc.gmp.model.basemodel.Org;
import com.pbc.gmp.model.basemodel.Position;
import com.pbc.gmp.model.basemodel.Role;
import com.pbc.gmp.model.basemodel.User;
import com.pbc.gmp.model.selectModelVo.selectUserVo;
import com.pbc.gmp.service.IOrgService;
import com.pbc.gmp.service.IRoleService;
import com.pbc.gmp.service.IUserService;
import com.pbc.gmp.service.impl.PositionServiceImpl;
import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.system.UserInfo;
import org.apache.shiro.SecurityUtils;

import org.springframework.beans.factory.annotation.Autowired;
import  com.pbc.gmp.commons.shiro.PasswordHash;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *   前端控制器
 * </p>
 *
 * @author kjk
 * @since 2017-04-17
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;
    @Autowired

    private PasswordHash passwordHash;
    @Autowired private IRoleService roleService;
    @Autowired private IOrgService orgService;
    @Autowired private PositionServiceImpl positionService;
    /**
     * 进入人员管理页面
     *
     * @return
     */
    @RequestMapping(value="/manager")
    public String manager() {
        return "admin/user/userList";
    }
    /**
     * 进入添加人员管理页面
     *
     * @return
     */
    @RequestMapping(value="/addPage")
    public String addPage() {
        return "admin/user/userAdd";
    }
    @RequestMapping(value="/usersList")
    @ResponseBody
    public Object userList(selectUserVo userVo, Integer page, Integer rows, String sort, String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        if(userVo!=null ||userVo.getSex()==2)
        {
            userVo.setSex(null);
        }
        if( userVo!=null || userVo.getEnabled()==2)
        {
            userVo.setEnabled(null);
        }
        if (StringUtils.isNotBlank(userVo.getLoginname())) {
            condition.put("loginName", userVo.getLoginname());
        }
        if (userVo.getUserOrganizationId() != null) {
            condition.put("organizationId", userVo.getUserOrganizationId());
        }else {
            LoginUserInfo userInfo=(LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
            condition.put("organizationId",userInfo.getOrgTreeDtos().get(0).getId());
        }
        if (userVo.getDepartmentid() != null) {
            condition.put("departmentid", userVo.getDepartmentid());
        }
        if (userVo.getSex() != null ) {
            condition.put("sex", userVo.getSex());
        }
        if (userVo.getEnabled() != null ) {
            condition.put("enabled", userVo.getEnabled());
        }
        pageInfo.setCondition(condition);
        userService.selectUserDetialInfoPage(pageInfo);
//        List<UserDetialInfo> list=userService.selectUserDetialInfoList();
        return pageInfo;
    }
    @RequestMapping(value="/selectUsersListByOrgId")
    @ResponseBody
    public List<UserDetialInfo> selectUsersListByOrgId(@RequestParam("id") Long id) {
        Org org=orgService.selectById(id);
        if (org.getManagertype() == 1) {
            return userService.selectUserDetialInfoListByOrgId(id);
        }
        if (org.getManagertype() == 2) {
            return userService.selectUserDetialInfoListByDepId(id);

        }
        return null;

    }
    @RequestMapping(value="/selectUsersSimpleListByDepId")
    @ResponseBody
    public List<UserDetialInfo> selectUsersSimpleListByOrgId(@RequestParam("id") Long id) {
        return userService.selectUserSimpleInfoListByDepId(id);


    }

    /**
     * 添加用户
     *
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/add", method = {RequestMethod.POST })
    @ResponseBody
    public Object add(UserDetialInfo userVo) {
        Wrapper whr=new EntityWrapper();
        whr.eq("loginname",userVo.getLoginname());
        List<User> list = userService.selectList(whr);
        if (list != null && !list.isEmpty()) {
            return renderError("登录名已存在!");
        }
        String salt = StringUtils.getUUId();
        String pwd = passwordHash.toHex(userVo.getPassword(), salt);
        userVo.setId(Convert.toLong(0));
        userVo.setSalt(salt);
        userVo.setPassword(pwd);
        userService.insertUserVo(userVo);

        return renderSuccess("添加成功");
    }
    /**
     * 进入更新用户
     */
    @RequestMapping(value="/editPage")
    public String editPage(Model model, @RequestParam Long id) {

        User user1 = userService.selectById(id);
        UserDetialInfo user =new UserDetialInfo();
        BeanUtils.copy(user1,user);
        Position position=positionService.selectPositionByUserId(user.getId());
        if(position==null)
        {
            user.setPositionid(Convert.toLong(0));
        }else {
            user.setPositionid(position.getId());
        }


        Set<Role> rolesList = roleService.selectRoleListByUserId(user.getId());
        List<Org> orgList=orgService.selectOrgListByUserId(user.getId());

        List<Long> ids = new ArrayList<Long>();
        if(rolesList != null && !rolesList.isEmpty())
        {
            for (Role role : rolesList) {
                ids.add(role.getId());
            }
        }
        List<Long> oids = new ArrayList<Long>();
        if(orgList != null && !orgList.isEmpty())
        {
            for (Org orgInfoVo : orgList) {
                oids.add(orgInfoVo.getId());
            }
        }

        model.addAttribute("roleIds", ids);
        model.addAttribute("user", user);
        model.addAttribute("orgIds",oids);
        return "admin/user/userEdit";
    }
    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/edit", method = {RequestMethod.POST })
    @ResponseBody
    public Object edit(UserDetialInfo user) {

        // 更新密码
        if (StringUtils.isBlank(user.getPassword())) {
//            User userVo = userService.selectById(user.getId());
//            String salt = userVo.getSalt();
//            String pwd = passwordHelper.toHex(user.getPassword(), salt);
//            user.setPassword(pwd);
            User userVo = userService.selectById(user.getId());
            user.setPassword(userVo.getPassword());
            user.setSalt(userVo.getSalt());

        }else {
            String salt = StringUtils.getUUId();
            user.setSalt(salt);
            String pwd=passwordHash.toHex(user.getPassword(),user.getSalt());
            user.setPassword(pwd);


        }
        userService.updateByVo(user);

        return renderSuccess("更新成功");
    }
    /**
     * 删除用户
     *
     * @param ids
     * @return
     */

    @RequestMapping(value = "/deleteUser", method = {RequestMethod.POST })
    @ResponseBody
    public Object delete(String ids) {

        userService.deleteBatchByIds(ids);
        return renderSuccess("删除成功！");
    }
    /**
     * 启用用户
     *
     * @param ids
     * @return
     */

    @RequestMapping(value = "/enableUser", method = {RequestMethod.POST })
    @ResponseBody
    public Object enableUser(String ids) {

        userService.updateEnableUserByIds(ids);
        return renderSuccess("删除成功！");
    }
    @RequestMapping(value = "/unableUser", method = {RequestMethod.POST })
    @ResponseBody
    public Object unableUser(String ids) {

        userService.updateUnableUserByIds(ids);
        return renderSuccess("删除成功！");
    }
    @RequestMapping(value = "/repwd", method = {RequestMethod.POST })
    @ResponseBody
    public Object rePwd(Long id) {

        userService.updateUserDefaultPwdById(id);
        return renderSuccess("重置成功！");
    }


}
